/*
 *  Copyright (C) 2021 the original author or authors.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package we.plugin.api.key;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import we.plugin.FizzPluginFilter;
import we.plugin.FizzPluginFilterChain;
import we.spring.http.server.reactive.ext.FizzServerHttpRequestDecorator;

import java.util.Map;

/**
 * @author liuwenchao
 */
@Slf4j
@Component(ApiKeyPluginFilter.APP_ID_PLUGIN_FILTER)
public class ApiKeyPluginFilter implements FizzPluginFilter {

    public static final String APP_ID_PLUGIN_FILTER = "apiKeyPlugin";

    public static final String FIZZ_GATEWAY_API_KEY = "Fizz-Gateway-Api-Key";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, Map<String, Object> config) {
        FizzServerHttpRequestDecorator request = (FizzServerHttpRequestDecorator) exchange.getRequest();

        final String fizzGatewayAppId = (String)config.get("fizzGatewayApiKey");

        request.getHeaders().add(FIZZ_GATEWAY_API_KEY, fizzGatewayAppId);

        return FizzPluginFilterChain.next(exchange);
    }


}
